<template>
	<view class="iphonex">
		<view class="a">
			<!-- 显示 modelDetail -->
			<view class="model-detail" v-if="modelDetail">
				<text>{{ modelDetail }}</text>
			</view>
			<!-- <view class="search">
				<icon type="search" size="16" color="#999" />
				<view class="uni-flex-item">
					<input type="text" @input="getSearch" v-model="searchVal" class="uni-input" placeholder="输入关键字进行搜索" />
				</view>
			</view> -->
			<u-search searchIconSize="44" height="70" placeholder="输入关键字进行搜索" v-model="keyword" @change="getSearch"
				@custom="getSearch"></u-search>
			<view class="flex-row row-center" @touchstart="streamRecord" @touchend="endStreamRecord">
				<u-icon name="mic" size="42" color="#2979ff"></u-icon>
			</view>
		</view>
		<view class="address-book-container" v-if="!keyword">
			<!-- 左侧通讯录 -->
			<scroll-view class="scroll-container uni-list" scroll-y="true" :scroll-into-view="toView"
				scroll-with-animation="true">
				<view class="uni-list" v-for="(p, i) in list" :key="i" :id="p.id">
					<view class="uni-list-cell pd-20 title">{{ p.id }}</view>
					<view class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in p.brands" :key="index"
						@click="goUrl('/pages/home/carlist/index?brandId=' + item.brandId + '&title=' + item.showName)">
						<img class="contact-img" :src="item.brandLogo" alt="" />
						<view class="uni-list-cell-db">
							<view class="contact-name">{{ item.showName }}</view>
							<!--<view class="contact-address">{{ item.address }}</view>
		            <view class="contact-phone">{{ item.phone }}</view> -->
						</view>
					</view>
				</view>
			</scroll-view>

			<!-- 右侧字母导航条 -->
			<view class="letter-nav">
				<view :class="['item',Inv== index?'on':'']" v-for="(item, index) in indexList" :key="index"
					@click="toSelectIndex(item)">
					{{ item }}
				</view>
			</view>
		</view>
		<view v-else-if="searchList.length > 0" class="address-book-container">
			<!-- 左侧通讯录 -->
			<scroll-view class="scroll-container uni-list" scroll-y="true" scroll-with-animation="true">
				<view class="uni-list" v-for="(p, i) in searchList" :key="i" :id="p.id">
					<view class="uni-list-cell pd-20 title">{{ p.showName }}</view>
					<view class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in p.models" :key="index"
						@click="onSaleNameChange(item.modelId, 'yearRight', p.secondBrand + item.modelName)">
						<view class="uni-list-cell-db">
							<view class="contact-name">{{ item.modelName }}</view>
							<!--<view class="contact-address">{{ item.address }}</view>
		            <view class="contact-phone">{{ item.phone }}</view> -->
						</view>
					</view>
				</view>
			</scroll-view>
			<!-- @click="goUrl('/pages/home/detail/index?modelId=' + item.modelId + '&title=' +  p.brandName + item.modelName)" -->

			<!-- 右侧字母导航条 -->
			<view class="letter-nav">
				<view :class="['item',Inv== index?'on':'']" v-for="(item, index) in indexList" :key="index"
					@click="toSelectIndex(item)">
					{{ item }}
				</view>
			</view>
		</view>
		<view v-else>
			<u-empty mode="favor" icon="../../../../static/images/comment.png" text="暂无内容" width="320" height="320"
				textSize="24"></u-empty>
		</view>
		<uni-drawer ref="yearRight" :width="200" mode="right">
			<view class="scroll-view">
				<scroll-view class="scroll-view-box" scroll-y="true">
					<view class="info-content" @click="getSaleNameByModelId(cc)" v-for="cc in saleCC" :key="cc">
						<text>{{cc}}</text>
					</view>
				</scroll-view>
			</view>
		</uni-drawer>
		<uni-drawer ref="showRight" :width="200" mode="right">
			<view class="scroll-view">
				<scroll-view class="scroll-view-box" scroll-y="true">
					<view class="info-content" @click="goCarDetail(item)" v-for="item in saleNames" :key="item">
						<text>{{item}}</text>
					</view>
				</scroll-view>
			</view>
		</uni-drawer>
		<view class="title" style="text-align: center;margin-top: 50px;background-color: transparent;">按住说出品牌车系,如奥迪A6
		</view>
		<view :class="['flex-row', 'row-center', 'fixed-mic', {active: isRecording}]" @touchstart="streamRecord"
			@touchend="endStreamRecord">
			<u-icon name="mic" size="200" :color="micColor"></u-icon>
		</view>

		<!-- <view class="footer flex-row row-center" v-show="isShow" @touchstart="streamRecord" @touchend="endStreamRecord">
			<u-icon name="mic" size="100" color="#2979ff"></u-icon>
		</view> -->
	</view>

</template>

<script>
	let plugin = requirePlugin("WechatSI");
	let manager = plugin.getRecordRecognitionManager();
	import {
		HEADER,
		HTTP_REQUEST_URL,
	} from '@/config/app';
	import {
		getSaleNameByModelId,
		getCCByModelId
	} from '@/api/car.js';
	import {
		mapGetters
	} from "vuex";
	import {
		toLogin
	} from '@/libs/login.js';
	import {
		getBrand
	} from '@/api/car.js';
	export default {

		data() {
			return {
				selectSaleName: '',
				selectCC: '',
				modelId: 0,
				title: '',
				saleNames: [], // 去重后的销售版本名称
				saleCC: [], // 当前选中的销售版本对应的年份
				indexList: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
					'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
				],
				toView: '',
				isRecording: false, // 录音状态
				list: [],
				searchList: [],
				keyword: '',
				// isShow: false
				modelDetail: '',
				debounceTimeout: null, // 防抖用的定时器
				currentRequestId: 0, // 请求的唯一标识符
			}
		},
		onLoad(options) {
			this.getBrand();
			this.initRecord();
			// 获取传递的 keyword 参数并执行搜索
			if (options.keyword) {
				this.keyword = options.keyword;
				this.getSearch(this.keyword);
			}
			if (options.modelDetail) {
				this.modelDetail = options.modelDetail;
				console.log(this.modelDetail)
			}
		},
		onShow() {

		},
		computed: {
			...mapGetters({
				isLogin: 'isLogin'
			}),
			// 动态设置图标的颜色
			micColor() {
				return this.isRecording ? '#ff0000' : '#009800'; // 录音时红色，未录音时绿色
			}
		},
		methods: {
			goCarDetail(saleName) {
				if (this.isLogin == false) {
					toLogin();
					return;
				}
				this.selectSaleName = saleName;
				this.$util.Tips('/pages/home/detail/index?modelId=' + this.modelId + '&saleName=' + this.selectSaleName +
					'&cc=' + this.selectCC + '&title=' + this.title)
			},
			onSaleNameChange(modelId, e, title) {
				this.saleNames = [];
				this.saleCC = [];
				let that = this;
				this.modelId = modelId;
				this.title = title
				getCCByModelId({
					modelId: this.modelId,
				}).then(res => {
					this.saleCC = res.value;
				})
				this.$refs[e].open()
			},
			getSaleNameByModelId(cc) {
				this.selectCC = cc;
				getSaleNameByModelId({
					modelId: this.modelId,
					cc: cc
				}).then(res => {
					this.saleNames = res.value;
					if (this.saleNames.length === 0) {
						if (this.isLogin == false) {
							toLogin();
							return;
						}
						this.selectSaleName = '';
						this.$util.Tips('/pages/home/detail/index?modelId=' + this.modelId + '&saleName=' + this
							.selectSaleName + '&cc=' + this.selectCC + '&title=' + this.title)
					} else {
						this.$refs["showRight"].open();
					}
				}).catch(err => {
					that.$util.Tips({
						title: err
					})
				})
			},
			//
			back() {
				uni.navigateBack({
					delta: 1
				});
			},
			goToPage(url) {
				if (!url) return;
				uni.navigateTo({
					url
				});
			},
			//
			toSelectIndex(item, Inv) {
				this.toView = item
				this.navIdx = Inv;
			},
			/**
			 * 获取所有车灯品牌
			 */
			getBrand() {
				let that = this;
				getBrand().then(res => {
					that.list = res.value;
				}).catch(err => {
					that.$util.Tips({
						title: res.message
					});
				})
			},
			/**
			 * 跳转到品牌车系详情
			 * @param {String} url
			 */
			goUrl(url) {
				this.$util.Tips(url);
			},

			// 监听输入框的值变化，进行防抖搜索
			onKeywordChange(e) {
				const newKeyword = e.detail.value; // 获取输入框的值
				this.keyword = newKeyword;

				// 清除之前的定时器，实现防抖
				if (this.debounceTimeout) {
					clearTimeout(this.debounceTimeout);
				}

				// 开启一个新的定时器，延迟300ms发起请求
				this.debounceTimeout = setTimeout(() => {
					this.getSearch(newKeyword);
				}, 300);
			},

			// 发起搜索请求
			getSearch(keyword) {
				if (!keyword.trim()) {
					this.searchList = []; // 如果关键字为空，直接清空列表
					return;
				}

				const requestId = ++this.currentRequestId; // 标记当前请求
				const that = this;

				uni.request({
					url: HTTP_REQUEST_URL + "/api/car/getKey",
					//url: HTTP_REQUEST_URL + "/car/getKey",
					method: "GET",
					data: {
						keyWord: keyword
					},
					success(res) {
						// 仅处理最后一次发起的请求
						if (requestId === that.currentRequestId) {
							that.searchList = res.data.value || []; // 更新搜索结果
						}
					},
					fail(err) {
						if (requestId === that.currentRequestId) {
							uni.showToast({
								title: "搜索失败",
								icon: "none",
							});
						}
					},
				});
			},

			/**
			 * 显示语音图标
			 */
			// focus(e) {
			// 	this.isShow = true;
			// },

			/**
			 * 语音插件
			 */
			streamRecord() {
				let that = this;
				this.isRecording = true; // 按下时显示录音状态
				uni.getSetting({
					success(res) {
						console.log(res);
						if (res && res.authSetting && res.authSetting.hasOwnProperty('scope.record')) {
							if (res.authSetting['scope.record']) {
								manager.start({
									lang: 'zh_CN',
								});
							} else {
								uni.showModal({
									content: '检测到您还没打开麦克风，是否去设置打开？',
									confirmText: "确认",
									cancelText: "取消",
									success: function(res) {
										if (res.confirm) {
											uni.openSetting({
												success(res) {
													console.log(res);
													manager.start({
														lang: 'zh_CN',
													})
												}
											});
										}
									}
								})

							}
						} else {
							manager.start({
								lang: 'zh_CN',
							})
						}
					}
				});

			},

			endStreamRecord() {
				this.isRecording = false; // 松开时隐藏录音状态
				console.log('=======结束====')
				manager.stop()
			},
			/**
			 * 
			 */
			initRecord() {
				//有新的识别内容返回，则会调用此事件
				manager.onRecognize = (res) => {
					this.isRecording = true; // 按下时显示录音状态
					let text = res.result
					console.log()
					this.keyword = text.replace("。", "")
				}
				// 识别结束事件
				manager.onStop = (res) => {
					this.isRecording = false; // 松开时隐藏录音状态
					let text = res.result
					if (text == '') {
						console.log('没有说话')
						return
					}
					this.keyword = text.replace("。", "")
				}
			},
		}
	}
</script>

<style>
	// 处理抽屉内容滚动
	.scroll-view-box {
		flex: 1;
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
	}

	.info-content {
		padding: 10px 15px;
		border-bottom: 1px solid #eaeaea;
		/* 添加下划线 */
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: #ffffff;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		/* 添加阴影效果 */
		transition: all 0.3s ease;
		/* 添加过渡效果 */
		cursor: pointer;
	}

	.a {
		padding: 30rpx;
		position: relative;
		z-index: 9;
		display: flex;
		align-items: center;
	}

	.a .search {
		padding: 0 20rpx;
		display: flex;
		align-items: center;
		background: #F6F7F9;
		border-radius: 60rpx;
	}

	.a .search input {
		background: none;
	}

	.uni-list:after,
	.uni-list::before {
		display: none;
	}

	.title {
		background: #F6F7F9;
	}

	.contact-img {
		width: 70rpx;
		height: 70rpx;
		margin-right: 20rpx;
	}

	.scroll-container {
		height: 56vh;
	}


	.letter-nav {
		background: #F6FAF9;
		border-radius: 20rpx;
		text-align: center;
		padding: 10rpx;
		z-index: 99;
		position: fixed;
		right: 20rpx;
		top: 50%;
		transform: translate(0, -50%);
		color: #B2B2B2;
		font-size: 20rpx;
		line-height: 30rpx;
	}

	.letter-nav .item:hover {
		color: #06A972;
	}

	.pd-20 {
		padding: 10rpx 20rpx;
	}

	//麦克风样式
	.fixed-mic {
		position: fixed;
		bottom: 50px;
		left: 50%;
		transform: translateX(-50%);
		z-index: 0;
		background-color: #ffffff;
		padding: 10px;
		border-radius: 50%;
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
	}

	.mic-icon {
		position: relative;
		z-index: 2;
	}

	/* 激活时光圈动画 */
	.fixed-mic.active::after {
		content: '';
		position: absolute;
		top: 50%;
		left: 50%;
		width: 120px;
		/* 光圈的大小 */
		height: 120px;
		/* 光圈的大小 */
		margin-top: -60px;
		/* 通过负值偏移，确保光圈垂直居中 */
		margin-left: -60px;
		/* 通过负值偏移，确保光圈水平居中 */
		border-radius: 50%;
		background-color: rgba(0, 152, 0, 0.2);
		/* 绿色光圈 */
		opacity: 0;
		transform: scale(0);
		/* 初始状态下的缩放 */
		animation: pulse 1.5s ease-out infinite;
		/* 无限循环的动画 */
		pointer-events: none;
		z-index: 1;
	}


	/* 激活时光圈动画 */
	.fixed-mic.active::before {
		content: '';
		position: absolute;
		top: 50%;
		left: 50%;
		width: 120px;
		/* 光圈的大小 */
		height: 120px;
		/* 光圈的大小 */
		margin-top: -60px;
		/* 通过负值偏移，确保光圈垂直居中 */
		margin-left: -60px;
		/* 通过负值偏移，确保光圈水平居中 */
		border-radius: 50%;
		background-color: rgba(0, 152, 0, 0.2);
		/* 绿色光圈 */
		opacity: 0;
		transform: scale(0);
		/* 初始状态下的缩放 */
		animation: pulse2 1.5s ease-out infinite;
		/* 无限循环的动画 */
		pointer-events: none;
		z-index: 1;
	}

	@keyframes pulse {
		0% {
			opacity: 0.2;
			transform: scale(0);
		}

		50% {
			opacity: 0.7;
			transform: scale(1.5);
			/* 光圈最大扩展 */
		}

		100% {
			opacity: 0;
			transform: scale(2.5);
			/* 光圈最终消失 */
		}
	}

	@keyframes pulse2 {
		0% {
			opacity: 0.1;
			transform: scale(0);
		}

		50% {
			opacity: 0.4;
			transform: scale(2);
			/* 第二层光圈最大扩展 */
		}

		100% {
			opacity: 0;
			transform: scale(3);
			/* 第二层光圈最终消失 */
		}
	}

	.model-detail {
		position: fixed;
		/* 悬浮定位 */
		top: 800rpx;
		/* 距离顶部20px */
		left: 50%;
		/* 居中显示 */
		transform: translateX(-50%);
		/* 完全居中 */
		background-color: rgba(0, 0, 0, 0.7);
		/* 背景色可根据需要修改 */
		color: white;
		padding: 10px;
		border-radius: 5px;
		z-index: 9999;
		/* 确保悬浮在其他元素之上 */
	}

	.model-detail-text {
		font-size: 16px;
		word-wrap: break-word;
		/* 防止文字溢出 */
	}
</style>